<template>
  <ie-page :loading="loading">

    <template #extra>
      <n-space>
        <n-popconfirm :on-positive-click="back">
          <template #trigger>
            <n-button>取消</n-button>
          </template>
          是否取消，当前编写内容不会被保存？
        </n-popconfirm>
        <template v-if="isEditing">
          <n-button @click="handleReset">撤销修改</n-button>
          <n-divider vertical style="height: 34px;" />
        </template>
        <n-button @click="handleConfirm" type="primary">保存</n-button>
      </n-space>
    </template>

    <ie-form
      :model="UserModel"
      :passby="passby"
      ref="formRef"
    />
  </ie-page>
</template>

<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useNotification } from 'naive-ui'
import { isEmpty } from 'lodash-es'

import UserModel from '/@/model/user'
import { useApi } from '/@/api'
import { useGraphqlClient, createPkQuery } from '/@/graphql'

const formRef = ref()
const loading = ref(false)

const route = useRoute()
const router = useRouter()
const notify = useNotification()

const isEditing = !isEmpty(route.params)
const passby = []

if (isEditing) {
  passby.push('password')
  loading.value = true
  useGraphqlClient().executeQuery({
    query: createPkQuery(UserModel, 'id', 'uuid'),
    variables: route.params
  }).then(res => {
    if (!res.error) {
      const [data] = res.data?.ie_user || []

      if (data) {
        formRef.value.set(data)
      } else {
        back()
      }
    }
    loading.value = false
  })
}

function back() {
  router.push({ name: 'User' })
}

function handleReset() {
  formRef.value.reset()
}

function handleConfirm() {
  const onOk = (resp, content = '成功') => {
    if (resp.code === 0) {
      notify.success({
        content,
        meta: '即将跳到列表页',
        duration: 5e3,
        onAfterEnter: back
      })
    }
  }

  formRef.value.submit()
    .then(values => {
      if (isEditing) {
        return useApi()
          .post('user/update', {
            ...values,
            ...route.params
          })
          .then(res => onOk(res, '修改用户成功'))
      }

      useApi()
        .post('user/create', values)
        .then(res => onOk(res, '新建用户成功'))
    })
}
</script>